using System;
using System.Text;
using System.IO;
using System.Xml;
using System.Xml.Serialization;

namespace SXDClient.Helpers
{
    public static class ObjectSerializer
    {

        public static string ObjToXmlStr(object obj)
        {
            if (obj == null)
                return String.Empty;

            XmlSerializer sr = new XmlSerializer(obj.GetType());
            MemoryStream memoryStream = new MemoryStream();
            try
            {
                XmlTextWriter xmlTextWriter = new XmlTextWriter(memoryStream, Encoding.UTF8);
                sr.Serialize(xmlTextWriter, obj);
                memoryStream = (MemoryStream)xmlTextWriter.BaseStream;

                return Encoding.UTF8.GetString(memoryStream.ToArray());
            }
            catch
            {
                return String.Empty;
            }
        }

        public static T XmlStrToObj<T>(string xmlStr)
        {
            if (String.IsNullOrEmpty(xmlStr))
                return default(T);

            try
            {
                XmlSerializer sr = new XmlSerializer(typeof(T));
                MemoryStream memoryStream = new MemoryStream(Encoding.UTF8.GetBytes(xmlStr));
             
                return (T)sr.Deserialize(memoryStream);
            }
            catch
            {
                return default(T);
            }
        }

    }
}
